package com.zsp.coupon.schedule;


import com.zsp.coupon.dao.CouponTemplateDao;
import com.zsp.coupon.entity.CouponTemplate;
import com.zsp.coupon.vo.TemplateRule;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <h1>定时清理已过期的优惠券模板</h1>
 * Created by Qinyi.
 */
@Component
public class ScheduleTask {
 private  final CouponTemplateDao templateDao;


 @Autowired
    public ScheduleTask(CouponTemplateDao templateDao) {
        this.templateDao = templateDao;
    }

    /**
     * 下线过期的优惠版模板
     */
    @Scheduled(fixedDelay = 60*60 *1000)
    public  void  offLineCouponTemplate() {
        System.out.println("Start  to expired Coupontemplate");
   List<CouponTemplate>  templates=templateDao.findAllByExpired(false);
        if (CollectionUtils.isEmpty(templates)){
            System.out.println("Done TO Exipred CouponTempalte");
            return;
        }
        Date current=new Date();
        List<CouponTemplate> expiredtemplates =
                new ArrayList<>(templates.size());
        templates.forEach(t ->{
            //根据优惠卷模板中的过期规则
               TemplateRule rule= t.getRule();
               if (rule.getException().getDeadline() <current.getTime()){
                   t.setExpired(true);
                   expiredtemplates.add(t);
               }
        });
        if (CollectionUtils.isNotEmpty(expiredtemplates)){
            System.out.println("EXPIRED couponTemplate num"+
                    templateDao.saveAll(expiredtemplates));
        }
        System.out.println("Done TO Exipred CouponTempalte");
    }
}
